import { defineStore } from 'pinia'
import request from '@/utils/request'
import { ApiRes, CateItem, TopCategory, SubCategory } from '@/types/data'
import { topCategory } from '../constants'

const defaultValue = topCategory.map((item) => {
  return {
    name: item,
  }
})
// console.log(defaultValue)

export default defineStore('category', {
  state() {
    return {
      // money: 100,
      list: defaultValue as CateItem[],
      topCategory: {} as TopCategory, // 一级分类的信息对象存下来
      subCategory: {} as SubCategory, // 二级分类的信息对象
    }
  },
  actions: {
    async getAllCategory() {
      const res = await request.get<ApiRes<CateItem[]>>('/home/category/head')
      // console.log(res.data.result)
      // 添加一个字段 配合后面点击隐藏的需求
      res.data.result.forEach((item) => {
        // 表示一级分类的layer是否显示隐藏
        item.flag = false
      })
      this.list = res.data.result
    },

    // 显示一级的layer
    show(id: string) {
      const itemObj = this.list.find((item) => item.id === id) // 找不到就会返回undefined
      itemObj!.flag = true
    },
    // 隐藏一级的layer
    hide(id: string) {
      const itemObj = this.list.find((item) => item.id === id) // 找不到就会返回undefined
      itemObj!.flag = false
    },

    // 根据一级的id  获取一级分类的详情对象
    async getTopCategory(id: string) {
      const res = await request.get<ApiRes<TopCategory>>('/category?id=' + id)
      this.topCategory = res.data.result
    },
    // 根据二级id
    async getSubFilter(id: string) {
      const res = await request.get<ApiRes<SubCategory>>(
        '/category/sub/filter',
        {
          params: {
            id,
          },
        }
      )
      this.subCategory = res.data.result
    },
  },
})
